﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ComponentGo.Web;
using System.IO;

namespace WebSchedulerDemo.xml {
	public partial class PlanItem : System.Web.UI.Page {
		PlanDataSet ds;
		string fileName;

		PlanDataSet.PlanItemRow row;

		protected void Page_Load(object sender, EventArgs e) {
			Response.Cache.SetCacheability(HttpCacheability.NoCache);

			if (Request["id"]=="null")
				Server.Transfer("default.aspx");

			//
			// Load from XML file
			//
			ds = new PlanDataSet();
			fileName = MapPath("../App_Data/ProjectsPlanner.xml");
			if (File.Exists(fileName))
				ds.ReadXml(fileName);

			if (string.IsNullOrEmpty(Request["id"])) {
				row = ds.PlanItem.NewPlanItemRow();
				row.DateBegin = JScriptTools.GetDate(long.Parse(Request["dt"]));
				row.DateEnd = row.DateBegin.AddDays(1);
				row.Project_ID = int.Parse(Request["row"]);
				row.Name = "New item";
				row.Busy = false;
				row.Important = false;
				ds.PlanItem.AddPlanItemRow(row);
				IDLabel.Text = "New item";
			}
			else {
				int id = int.Parse(Request["id"]);
				row = ds.PlanItem.FindByPlanItem_ID(id);
				IDLabel.Text = id.ToString();
			}

			if (!IsPostBack) {
				NameText.Text = row.Name;
				DateBeginText.Text = row.DateBegin.ToString();
				DateEndText.Text = row.DateEnd.ToString();
				ImportantCheck.Checked = row.Important;
				BusyCheck.Checked = row.Busy;
				if (row.IsColorNull())
					ColorDropList.SelectedIndex = 0;
				else
					ColorDropList.SelectedValue = row.Color;
			}
		}

		protected void SaveButton_Click(object sender, EventArgs e) {
			row.Name = NameText.Text;
			row.DateBegin = DateTime.Parse(DateBeginText.Text);
			row.DateEnd = DateTime.Parse(DateEndText.Text);
			row.Important = ImportantCheck.Checked;
			row.Busy = BusyCheck.Checked;
			if (ColorDropList.SelectedIndex==0)
				row.SetColorNull();
			else
				row.Color = ColorDropList.SelectedValue;

			ds.WriteXml(fileName);

			Response.Redirect("default.aspx");
		}
	}
}
